package test;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Cookie {

	private Map<String, String> cookies = new HashMap<String,String>();
	
	public void addCookie(String key, String value){
		cookies.put(key, value);
	}
	
	public String removeCookie(String key){
		return cookies.get(key);
	}
	
	public  void addCookieByString(String text){
		// 	PREF=ID=7423fe53ec60279e:FF=0:NW=1:TM=1324003956:LM=1324003956:S=-icitVE8BbJWJkGn; expires=Sun, 15-Dec-2013 02:52:36 GMT; path=/; domain=.google.com.hk NID=54=lkTGI3hEe346iVgL0SJjBVkT9MAkdOasZdJS31FHdlGSBdLrYSfuV3HWV1A1WF5K-5GkQpF_8F3BGcF4j1QyBjh5wDKk2BSc4icK-C1n7rFXuOVu786ORFCpjxa1g4RK; expires=Sat, 16-Jun-2012 02:52:36 GMT; path=/; domain=.google.com.hk; HttpOnly
		if(text == null)
			return;
		String[] arr = text.split(";");
		for(String cookie : arr){
			cookie = cookie.trim();
			int start = cookie.indexOf("=");
			if(start == -1){
				continue;
			}
			String name = cookie.substring(0, start);
			if(name.equalsIgnoreCase("expires") ||
					name.equalsIgnoreCase("path") ||
					name.equalsIgnoreCase("domain")){
				continue;
			}
			String value = cookie.substring(start + 1);
			cookies.put(name, value);
			break;
		}
	}
	
	public String toCookieString(){
		Set<String> keys = cookies.keySet();
		String text = "";
		for(String key : keys){
			if(cookies.get(key) != null){
				text = text + "; " +key+"=" + cookies.get(key);
			}
		}
		if(text.startsWith("; ")){
			text = text.substring(2);
		}
		return text;
	}
}
